package com.yy.permissions_general.security.handler;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.yy.permissions_general.module.system.aopLog.entity.SysLog;
import com.yy.permissions_general.module.system.aopLog.service.SysLogService;
import com.yy.permissions_general.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

/**
 * @Description: TODO 登录
 * @Author: YangYI
 * @Date: 2021/11/1
 **/
@Component
@Slf4j
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private SysLogService sysLogService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication authentication) throws IOException{
        //定义日志类型
        SysLog sysLog = new SysLog();
        sysLog.setLogType("INFO");
        sysLog.setTaskType(1);
        sysLog.setStartTime(new Date(System.currentTimeMillis()));
        sysLog.setExecuteTime(0l);
        sysLog.setEndTime(new Date(System.currentTimeMillis()));
        sysLog.setCreateUserCode(SecurityUtil.getCurrentUser().getAccount());
        sysLog.setCreateUserName(SecurityUtil.getCurrentUser().getUsername());
        sysLog.setBrowserName(LogUtils.getBrowser(httpServletRequest));
        sysLog.setRequestIp(LogUtils.getIp(httpServletRequest));
        sysLog.setRequestMethod(httpServletRequest.getMethod());
        sysLog.setServerAddress(httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort());
        String userAgentStr = httpServletRequest.getHeader("User-Agent");
        UserAgent userAgent = UserAgentUtil.parse(userAgentStr);
        sysLog.setDeviceName(userAgent.getOs().getName());
        sysLog.setUserAgent(userAgentStr);
        sysLog.setDescription("登录");
        sysLog.setRequestUrl(URLUtil.getPath(httpServletRequest.getRequestURI()));
        sysLog.setRequestParams(LogUtils.formatParams(httpServletRequest.getParameterMap()));
        sysLog.setIsException("0");
        sysLog.setCreateDate(new Date());
        sysLogService.save(sysLog);
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute("currentUser", authentication.getPrincipal());
        //删除缓存里的验证码信息
        session.removeAttribute("captcha");
        //输出结果
        ServletUtil.write(FastJsonUtils.toString(ResultUtil.success("登录成功~")));
    }
}
